package com.xsoft.sms.cmpp20.comm.handlers;

import com.xsoft.sms.cmpp20.message.ICMPP20Message;
import com.xsoft.sms.cmpp20.message.factory.CMPP20MessageBodyFactory;
import com.xsoft.sms.cmpp20.message.factory.CMPP20MessageFactory;
import com.xsoft.sms.cmpp20.message.impl.CMPP20Message;
import com.xsoft.sms.cmpp20.message.impl.CMPP20MessageHead;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;

/**
 * package: {PACKAGE_NAME}
 * User: zhanglm
 * Date: 12-9-18
 * Time: 下午2:43
 * Description:
 */
public class CMPP20MessageDecoder extends FrameDecoder {
	@Override
	protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
		if (buffer.readableBytes() < CMPP20Message.CMPP20_HEAD_LENGTH) {
			return null;
		}

		buffer.markReaderIndex();
		byte[] headBuffer = new byte[CMPP20Message.CMPP20_HEAD_LENGTH];
		buffer.readBytes(headBuffer);

		CMPP20MessageHead head = new CMPP20MessageHead();
		head.fromBuffer(headBuffer);

		int bodyLength = head.getTotalLength() - CMPP20Message.CMPP20_HEAD_LENGTH;
		if (buffer.readableBytes() < bodyLength) {
			buffer.resetReaderIndex();
			return null;
		}

		byte[] bodyBuffer = new byte[bodyLength];
		buffer.readBytes(bodyBuffer);

		ICMPP20Message body = CMPP20MessageBodyFactory.newCMPP20MessageBody(head.getCmdId());
		if (body == null) {
			return null;
		}
		body.fromBuffer(bodyBuffer);

		CMPP20Message message = CMPP20MessageFactory.newCmpp20Message(head.getCmdId());
		if (message == null) {
			return null;
		}

		message.setHead(head);
		message.setBody(body);
		return message;
	}

}
